/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.bpmn.behavior;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.DynamicBpmnConstants;
import com.je.bpm.engine.delegate.BpmnError;
import com.je.bpm.engine.delegate.DelegateExecution;
import com.je.bpm.engine.impl.bpmn.helper.ErrorPropagation;
import com.je.bpm.engine.impl.context.Context;
import com.je.bpm.engine.impl.scripting.ScriptingEngines;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * activity implementation of the BPMN 2.0 script task.
 */
public class ScriptTaskActivityBehavior extends TaskActivityBehavior {

    private static final long serialVersionUID = 1L;

    private static final Logger LOGGER = LoggerFactory.getLogger(ScriptTaskActivityBehavior.class);

    protected String scriptTaskId;
    protected String script;
    protected String language;
    protected String resultVariable;
    protected boolean storeScriptVariables = false; // see https://activiti.atlassian.net/browse/ACT-1626

    public ScriptTaskActivityBehavior(String script, String language, String resultVariable) {
        this.script = script;
        this.language = language;
        this.resultVariable = resultVariable;
    }

    public ScriptTaskActivityBehavior(String scriptTaskId, String script, String language, String resultVariable, boolean storeScriptVariables) {
        this(script, language, resultVariable);
        this.scriptTaskId = scriptTaskId;
        this.storeScriptVariables = storeScriptVariables;
    }

    @Override
    public void execute(DelegateExecution execution) {
        ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines();
        if (Context.getProcessEngineConfiguration().isEnableProcessDefinitionInfoCache()) {
            ObjectNode taskElementProperties = Context.getBpmnOverrideElementProperties(scriptTaskId, execution.getProcessDefinitionId());
            if (taskElementProperties != null && taskElementProperties.has(DynamicBpmnConstants.SCRIPT_TASK_SCRIPT)) {
                String overrideScript = taskElementProperties.get(DynamicBpmnConstants.SCRIPT_TASK_SCRIPT).asText();
                if (StringUtils.isNotEmpty(overrideScript) && !overrideScript.equals(script)) {
                    script = overrideScript;
                }
            }
        }

        boolean noErrors = true;
        try {
            Object result = scriptingEngines.evaluate(script, language, execution, storeScriptVariables);
            if (resultVariable != null) {
                execution.setVariable(resultVariable, result);
            }
        } catch (ActivitiException e) {
            LOGGER.warn("Exception while executing " + execution.getCurrentFlowElement().getId() + " : " + e.getMessage());
            noErrors = false;
            Throwable rootCause = ExceptionUtils.getRootCause(e);
            if (rootCause instanceof BpmnError) {
                ErrorPropagation.propagateError((BpmnError) rootCause, execution);
            } else {
                throw e;
            }
        }
        if (noErrors) {
            leave(execution);
        }
    }

}
